import os
import pathlib
import logging
from datetime import datetime
from config.config import Config

class Logger:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not hasattr(self, 'logger'):
            self.logger = self._init_logger()

    def _init_logger(self) -> logging.Logger:
        """初始化日志器"""
        logger = logging.getLogger('app_automation')
        logger.setLevel(Config.LOG_LEVEL)

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(Config.LOG_LEVEL)
        formatter = logging.Formatter(Config.LOG_FORMAT)
        console_handler.setFormatter(formatter)

        # 清理旧日志文件：先找到日志目录，删除目录下所有.log文件
        log_dir = pathlib.Path(__file__).parent.parent / 'logs'
        if log_dir.exists():
            for old_log in log_dir.glob('*.log'):
                old_log.unlink()  # 删除旧日志文件

        # 文件处理器：创建新的日志文件
        log_file = log_dir / f'{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
        os.makedirs(log_dir, exist_ok=True)
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(Config.LOG_LEVEL)
        file_handler.setFormatter(formatter)

        logger.addHandler(console_handler)
        logger.addHandler(file_handler)

        return logger

    def get_logger(self) -> logging.Logger:
        """获取日志器"""
        return self.logger


# 单例模式获取日志器
def get_logger() -> logging.Logger:
    return Logger().get_logger()